import React, { Component } from "react";

import { Link, Route, Switch, Redirect, withRouter } from "react-router-dom";

class Home extends Component {
  render() {
    return <div>这是home页面</div>;
  }
}
class About extends Component {
  render() {
    return <div>这是about页面</div>;
  }
}
class Mine extends Component {
  render() {
    return <div>这是我的页面</div>;
  }
}

@withRouter
class Login extends Component {
  fn = () => {
    localStorage.setItem("token", "123");
    // console.log(this.props);
    // 编程式导航用的是props的history的push/replace/go/goBack
    // this.props.history.push("/home");
    this.props.history.push(this.props.location.state.from);
  };

  render() {
    console.log(this.props);
    return (
      <div>
        这是登录页面 <button onClick={this.fn}>登录</button>
      </div>
    );
  }
}

// 路由鉴权的组件封装
const Auth = (props) => {
  return (
    <Route
      path={props.path}
      render={() => {
        if (localStorage.getItem("token")) {
          return props.children;
        } else {
          return (
            <Redirect
              to={{
                pathname: "/login",
                state: {
                  from: props.path,
                },
              }}
            ></Redirect>
          );
        }
      }}
    ></Route>
  );
};

class App extends Component {
  render() {
    return (
      <>
        <h2>react-router-v5-路由鉴权</h2>
        <ul>
          <li>
            <Link to="/home">首页</Link>
          </li>
          <li>
            <Link to="/about">关于页</Link>
          </li>
          <li>
            <Link to="/mine">我的页</Link>
          </li>
        </ul>

        <Switch>
          <Redirect from="/" to="/home" exact></Redirect>
          <Route path="/home" component={Home}></Route>
          {/* <Route path="/about" component={About}></Route> */}
          <Auth path="/about">
            <About />
          </Auth>
          {/* <Route
            path="/mine"
            render={() => {
              if (localStorage.getItem("token")) {
                return <Mine />;
              } else {
                return <Redirect to="/login"></Redirect>;
              }
            }}
          ></Route> */}
          <Auth path="/mine">
            <Mine />
          </Auth>
          <Route path="/login">
            <Login />
          </Route>
        </Switch>
      </>
    );
  }
}

export default App;
